package com.jms.tomcat.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/***
 * 静态资源处理工具类
 */
public class StaticResourceUtils {

    //静态资源缓存
    private static final Map<String, String> cache = new HashMap<>();

    public static void getStaticResource(HttpServletResponse response, String staticPath) throws IOException {
        PrintWriter printWriter = response.getWriter();
        if (cache.containsKey(staticPath)) {
            printWriter.write(cache.get(staticPath));
        } else {
            //获取静态资源流
            InputStream inputStream = StaticResourceUtils.class.getResourceAsStream(staticPath);
            if (inputStream != null) {
                //以字符形式读取静态资源
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder content = new StringBuilder();
                char[] bt = new char[1024];
                while (bufferedReader.ready()) {
                    int index = bufferedReader.read(bt);
                    content.append(bt, 0, index);
                }
                bufferedReader.close();
                printWriter.write(content.toString());
                //存入缓存
                cache.put(staticPath, content.toString());
            } else {
                //找不到资源则返回404
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        }
        printWriter.flush();
        printWriter.close();
    }
}
